# -*- coding: utf-8 -*-
'''
Created on 25/set/2009

@author: sax
'''

from admin import XModelAdminButton
from django.core.urlresolvers import reverse, resolve
from django.http import HttpResponse
from django.core import serializers

def query_string_filtered_button(view_name):
    """ return an XModelAdminButto mapped to ad url updated with 
        real time query_string parameter to view_name mapped url:
        
        es: if url is http://host.org/page?par1=val1&par=val2  
            and view_name is mapped to app/view
        
        return an XModelAdminButton mapped to app/view??par1=val1&par=val2
        
        used in th xadmin interface if is needed a button linked with 
        selected filter 
        
        use :
            def user_view(request):
                return ...
                
            class ClassAdmin(XModelAdmin):
                buttons = [ query_string_filtered_button(user_view)]
        

    """
    def inner(sender, request):    
        url = reverse( "%s:%s" % (sender.admin_site.name, view_name ))
        handler = resolve( url )
        label = getattr(handler[0], 'label', handler[0].__name__)
        return XModelAdminButton( label, "%s?%s" % (url, request.META['QUERY_STRING']) )

    return inner


def export_related_as_json(qs): #IGNORE:W0613    
    """Serializes the selected queryset and all related objects to JSON"""
    from django.db.models.query import CollectedObjects
    
    response = HttpResponse(mimetype="text/json")
    #response["Content-type"]= "application/vnd.ms-excel"
    #response["Content-Disposition"] = "attachment; filename=%s.json" % str(name).replace(" ", "_") 
    
    # Gather the related objects for each instance in the queryset.
    collected_objs = CollectedObjects()
    for obj in qs:
        obj._collect_sub_objects(collected_objs) #IGNORE:W0212
    
    # Collect all the instances into a list suitable for serialization.
    objs = []
    for x, objs_dict in collected_objs.items():  # co doesn't implement values IGNORE:W0612
        objs += objs_dict.values()
        
    serializers.serialize("json", objs, stream=response, indent=4)    
    return response
